import path = require("path");
import fs = require('fs');
import * as vscode from 'vscode';

export const supportFromFileExt = {
    ".ts": true,
    ".tsx": true,
    ".js": true,
    ".jsx": true,

    ".css": true,
    ".scss": true,
    ".sass": true,

    ".png": true,
    ".webp": true,
    ".jpg": true,
    ".jpeg": true,
};
export const supportToFileExt = {
    ".ts": true,
    ".tsx": true,
    ".js": true,
    ".jsx": true,
    ".scss": true,
    ".sass": true,
    ".vue": true,
    ".html": true,
    ".htm": true,
};

export function cmdInsertFileRefToActionEditor(fromFilePath: string, codeTemplate: string) {
    var err = insertFileRefToActionEditor(fromFilePath, codeTemplate);
    if (err) {
        vscode.window.showWarningMessage(err);
    }

    vscode.commands.executeCommand("workbench.action.focusActiveEditorGroup");
}
export function insertFileRefToActionEditor(fromFilePath: string, codeTemplate: string): string | null {
    var t = vscode.window.activeTextEditor;
    if (!t) return "当前没有激活的编辑器";
    var actTextEditor: vscode.TextEditor = t;
    var fromFileExt = path.extname(fromFilePath)?.toLocaleLowerCase();
    if (!fromFileExt) return "不支持没有文件后缀!";
    var editFile = actTextEditor.document.fileName;
    if (!fs.existsSync(editFile)) return "右侧文件未保存,无法计算相对路径!";

    return insertFileRef(fromFilePath, fromFileExt, editFile, actTextEditor, codeTemplate);
}
export function insertFileRef(fromFilePath: string, fromFileExt: string, toFilePath: string, txtEditor: vscode.TextEditor, codeTemplate: string): string | null {
    var fromFileNameNoExt = path.basename(fromFilePath, path.extname(fromFilePath))
    var editFileDir = path.dirname(toFilePath);
    var rePath = path.relative(editFileDir, fromFilePath).replace(/\\/g, '/');
    if (fromFileExt == ".ts") {
        // 来源是ts文件,则路径中后缀名可以忽略
        rePath = rePath.substring(0, rePath.length - 3);
    }
    if (!rePath.startsWith("../")) rePath = "./" + rePath;
    txtEditor.edit((editBuilder) => {
        //代码模板简单变量替换
        var code = codeTemplate
            .replace("{FromFileNameNoExt}", fromFileNameNoExt)
            .replace("{RePath}", rePath);
        //获取光标位置
        var position = new vscode.Position(txtEditor.selection.active.line, txtEditor.selection.active.character);
        //那行的文本
        var lineText = txtEditor.document.lineAt(position);
        var hasNewLine = false;
        if (lineText.text.trim().length > 0) {
            //如果不是空行,那么在光标位置的下一行开始,并插入一个回车
            code = "\r\n" + code;
            position = lineText.range.end;
            hasNewLine = true;
        }
        editBuilder.insert(position, code);
        var endPosition = new vscode.Position(position.line + (hasNewLine ? 1 : 0), code.length);
        setTimeout(()=>{
            txtEditor.selection = new vscode.Selection(position, endPosition);
        },100);
        
    });
    return null;
}